from datetime import timedelta

from aiogram_dialog import DialogManager
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.services.date_time import get_date_time
from app.config import Settings
from app.database.services.allowed_ips import get_allowed_ips
from app.database.services.orders.common import get_user_orders
from app.database.services.users import get_user


async def user_orders_getter(
    db_session: AsyncSession, dialog_manager: DialogManager, **kwargs
):

    user_id: int = dialog_manager.dialog_data.get("user_id")
    orders_status: str = dialog_manager.dialog_data.get("orders_status")
    orders_type: str = dialog_manager.start_data.get("orders_type")

    orders = await get_user_orders(
        db_session, user_id, orders_status=orders_status, orders_type=orders_type
    )

    return {
        "user_orders": orders,
        "count": len(orders),
    }


async def user_payments_getter(
    db_session: AsyncSession, dialog_manager: DialogManager, **kwargs
):

    user_id: int = dialog_manager.start_data.get("user_id")
    dialog_manager.dialog_data["user_id"] = user_id
    user = await get_user(db_session, user_id, joined=True)
    user_payments = user.payments

    return {
        "user_payments": user_payments,
        "count": len(user_payments),
    }


async def user_info_getter(
    db_session: AsyncSession, dialog_manager: DialogManager, **kwargs
):

    user_id: int = dialog_manager.middleware_data["event_from_user"].id
    config: Settings = dialog_manager.middleware_data.get("config")
    user = await get_user(db_session, user_id, joined=True)
    user_orders = user.orders
    date_now = get_date_time(get_datetime=True)
    if user.test_proxy_acquired:
        test_proxy_available = user.test_proxy_acquired <= date_now - timedelta(
            hours=24
        )
    else:
        test_proxy_available = True

    return {
        "user_orders": user_orders,
        "is_admin": user_id in config.tg_bot.admin_ids,
        "orders_count": len(user_orders),
        "user_id": user_id,
        "user_balance": user.balance,
        "user_email": user.email,
        "reg_date": user.was_registered,
        "test_proxy_available": test_proxy_available,
    }


async def user_ips_getter(
    db_session: AsyncSession, dialog_manager: DialogManager, **kwargs
):
    user_id: int = dialog_manager.middleware_data.get("event_from_user").id
    allowed_ips = await get_allowed_ips(db_session, user_id)

    return {
        "allowed_ips": allowed_ips,
        "count": len(allowed_ips),
    }
